<template>
  <div class="container">
    <!-- head -->
    <el-row class="box_head" :gutter="10">
      <el-col class="box_card" :span="8">
        <el-card style="height: 100%;">
          <div style="height:40px;line-height: 40px;" slot="header">
            <div class="left">电表</div>
            <div class="right">{{yesterDay}}</div>
          </div>
          <div>
            <el-row :gutter="10">
              <el-col :span="12">
                <div class="box_color">计量成功率</div>
                <div class="box_size">{{successRate*100}}%</div>
              </el-col>
              <el-col :span="12">
                <div class="box_color">计量失败数（个）</div>
                <div class="box_size">{{failCount}}</div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- body -->
    <el-row class="box_body" :gutter="10">
      <!-- left -->
      <el-col class="box_left" :span="17">
        <el-card>
          <!-- head -->
          <div style="height:50px; line-height: 50px;" slot="header">
            <div class="left">计量成功率</div>
            <!-- time -->
            <div class="right">
              <el-date-picker
                size="small"
                v-model="value1"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                @change="getSuccessRateList"
              ></el-date-picker>
            </div>
          </div>
          <!-- crnter -->
          <div class="center">
            <div class="empty" v-if="!isShow">{{text}}</div>
            <div id="line-chart" style="margin-bottom:20px;width: 100%;height: 560px;"></div>
          </div>
        </el-card>
      </el-col>
      <!-- right -->
      <el-col class="box_right" :span="7">
        <el-card>
          <div style="height:50px; line-height: 50px;" slot="header">
            <div class="left">计量失败列表</div>
          </div>
          <div class="center">
            <el-row :gutter="10">
              <!-- table1 -->
              <el-col style="font-size:14px; " :span="24">
                <div style="margin-bottom:15px;">
                  （1）昨日计量失败设备
                  <span style="float:right">
                    <el-link @click="exportExcel" type="success">导出明细</el-link>
                  </span>
                </div>
                <div>
                  <el-table border :data="failData" style="width: 100%">
                    <el-table-column prop="deviceTypeName" label="类型"></el-table-column>
                    <el-table-column prop="count" label="数量"></el-table-column>
                  </el-table>
                </div>
              </el-col>
              <!-- table2 -->
              <el-col style="font-size:14px;margin-top:40px;" :span="24">
                <div style="margin-bottom:15px;">
                  （2）最近一周内，连续3天计量失败设备
                  <span style="float:right">
                    <!-- <el-link type="success">导出明细</el-link> -->
                  </span>
                </div>
                <div>
                  <el-table border :data="nearWeekFailData" style="width: 100%">
                    <el-table-column prop="deviceTypeName" label="类型"></el-table-column>
                    <el-table-column prop="count" label="数量"></el-table-column>
                  </el-table>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import echarts from "echarts";
import {
  getFailList,
  getNearWeekFailList,
  getSuccessList,
  getSuccessRateList,
} from "@/api/measurement/measurement";
import { getToken } from "@/util/auth";
import { dateFormat } from "@/util/date";
export default {
  name: "measurement",
  data() {
    return {
      text: "请选择日期",
      isShow: false,
      yesterDay: "",
      value1: [],
      failData: [],
      failCount: "",
      successRate: "",
      nearWeekFailData: [],
      tableData1: [
        {
          date: "电表",
          name: "23",
        },
      ],
      line1: {
        instance: null,
      },
    };
  },
  created() {
    this.getCurrentMonthFirst();
    this.getFailList();
    this.getNearWeekFailList();
    this.getSuccessList();
    this.getYesterDay();
  },
  watch: {},
  // beforeUpdate() {
  //   this.$nextTick(() => {
  //     // this.initLineChart();
  //   });
  // },
  methods: {
    // 初始化日期
    getCurrentMonthFirst() {
      var date = new Date();
      date.setDate(1);
      console.log(" date.setDate(1);", date.getDate(1));
      var month = parseInt(date.getMonth() + 1);
      var day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      this.value1 = [
        date.getFullYear() + "-" + month + "-" + day,
        dateFormat(new Date(), "yyyy-MM-dd"),
      ];
      this.getSuccessRateList();
    },
    // 获取昨天日期
    getYesterDay() {
      let day1 = new Date();
      day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
      this.yesterDay =
        day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate();
    },
    // echarts-init
    initLineChart(data) {
      var dom = document.getElementById("line-chart");
      this.line1.instance = echarts.init(dom, {
        renderer: "svg", // 支持 'canvas' 或者 'svg'
        width: null, // 可显式指定实例宽度，单位为像素。如果传入值为 null/undefined/'auto'，则表示自动取 dom（实例容器）的宽度。
        height: null, // 可显式指定实例高度，单位为像素。如果传入值为 null/undefined/'auto'，则表示自动取 dom（实例容器）的高度。
      });
      this.line1.instance.setOption(this.getLineOpt(data));
      var self = this;
      window.addEventListener("resize", function () {
        self.line1.instance.resize();
      });
      self.line1.instance.resize();
    },
    // echarts配置
    getLineOpt(data) {
      var option = {};
      option = {
        color: ["#409EFF"],
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            return `${params[0].axisValue}<br />电表计量：${params[0].value}%`;
          },
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        legend: {
          data: ["降水量"],
        },
        xAxis: [
          {
            type: "category",
            name: "日期",
            // data: ["1月", "2月"],
            data: data.date,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "计量",
            min: 0,
            max: 100,
            interval: 50,
            axisLabel: {
              formatter: "{value} %",
            },
          },
        ],
        series: [
          {
            name: "电表计量",
            type: "bar",
            barWidth: 20,
            // data: [2.6, 5.9],
            data: data.successRate,
          },
        ],
      };
      return option;
    },
    // 导出昨日失败数据
    exportExcel() {
      console.log("exportExcel");
      let url = `/api/blade-meter/measurement/export-measure-failed-device?Blade-Auth=${getToken()}`;
      window.open(url, "_self");
    },
    // 昨日失败数
    async getFailList() {
      this.failData = [];
      const {
        data: { data },
      } = await getFailList();
      this.failCount = data.count;
      this.failData.push(data);
    },
    // 近一周失败数
    async getNearWeekFailList() {
      this.nearWeekFailData = [];
      const {
        data: { data },
      } = await getNearWeekFailList();
      this.nearWeekFailData.push(data);
    },
    // 昨日成功率
    async getSuccessList() {
      const {
        data: { data },
      } = await getSuccessList();
      this.successRate = data;
    },
    // 指定时间成功率
    async getSuccessRateList() {
      const {
        data: { data },
      } = await getSuccessRateList(this.value1[0], this.value1[1]);
      if (data.length > 0) {
        this.isShow = true;
        this.text = "请选择日期";
        let obj = {
          date: [],
          deviceTypeName: [],
          successRate: [],
        };
        data.forEach((item) => {
          obj.date.push(item.date);
          obj.deviceTypeName.push(item.deviceTypeName);
          obj.successRate.push(item.successRate * 100);
        });
        console.log(obj);
        this.initLineChart(obj);
      } else {
        this.text = "当前日期无数据";
        this.isShow = false;
      }
    },
  },
};
</script>

<style scoped lang='scss'>
.container {
  height: 100%;
  width: 100%;
}
.box_head {
  height: 25%;

  .box_card {
    height: 100%;
  }
  .right {
    color: #909399;
  }
}
.box_body {
  padding-bottom: 50px;
}
.box_color {
  color: #909399;
  font-size: 12px;
}
.box_size {
  font-size: 30px;
}

.box_left {
  .center {
    height: 560px;
  }
}

.box_right {
  .center {
    height: 560px;
    #line-chart {
    }
  }
}
.empty {
  margin: 0 auto;
  width: 100%;
  height: 20px;
  text-align: center;
  line-height: 20px;
  color: #e2e2e2;
}
</style>
